<script setup lang="ts">
import { computed, ref } from 'vue'
import VuePlayer from '@/components/player/VuePlayer.vue'
import Track from '@/components/map-trajectory/track.vue'
import RealTimeTrack from '@/components/map-realTime-track/realTimeTrack.vue'
import { useAlarmDataApi, useWaybillApi } from '@/api/biz/waybill'
import moment from 'moment'
import { avControl, avRequest, queryHistory } from '@/api/gps/jt808/jt1078'
import FreightTimeCount from '@/views/biz/waybill/freightTimeCount.vue'
import { useDeviceAndStatusApi } from '@/api/gps/device'
import { computeSubTitle, jt1078AvsetAnalysis } from '@/utils/gps/format'

const dialogVisible = ref(false)
const dataInfo = ref<any>()
const trackRef = ref()
const videoRefs = ref<any[]>([])
const activeName = ref('first')
const alarmData = ref([])
const freightRef = ref()
const deviceInfo = ref()

const getDateRange = computed(() => {
  return [dataInfo.value?.startTime, moment().format('YYYY-MM-DD HH:mm:ss')]
})
function init(id) {
  dialogVisible.value = true
  getWaybill(id)
}

/**
 * 获取运单信息
 * @param id
 */
function getWaybill(id: number) {
  useWaybillApi(id).then((res) => {
    dataInfo.value = res.data
    trackRef.value.getData([dataInfo.value?.planningTime, moment().format('YYYY-MM-DD HH:mm:ss')], dataInfo.value.imei, dataInfo.value.mineId)
    getAlarm(dataInfo.value.imei)
    if (dataInfo.value.status) {
      playerVideo(dataInfo.value.imei)
    }
    getHistoricalVideos()
  })
}

function getAlarm(imei) {
  useAlarmDataApi({
    page: 1,
    size: 100,
    imei,
    startTime: dataInfo.value.startTime,
    endTime: dataInfo.value.endTime
  }).then((res) => {
    alarmData.value = res.data.list
  })
}

/**
 * 播放全部
 */
function playerVideo(imei) {
  useDeviceAndStatusApi(imei).then((res) => {
    deviceInfo.value = res.data
    // const {
    //   attribute: { v_sig_lost: str },
    //   jt1078Avch
    // } = res.data
    // const arr: string[] = (str && str.split(',')) || []
    // let index = 0
    // for (let i = 0; i < parseInt(jt1078Avch); i++) {
    //   if (!arr.includes(i + 1 + '')) {
    //     avRequest(dataInfo.value.imei, i + 1, 1).then((res) => {
    //       videoRefs.value[index++].init(res.data.streamUrl)
    //     })
    //   }
    // }
    const channelNames = jt1078AvsetAnalysis(res.data.jt1078Avch, res.data.jt1078Avset)
    if (channelNames.length === 0) {
      return
    }
    let index = 0
    for (let i = 0; i < channelNames.length; i++) {
      let cl = channelNames[i]
      avRequest({
        imei: dataInfo.value.imei,
        channel: cl.channel,
        streamType: 1,
        mediaType: 0}).then((res) => {
        videoRefs.value[index++].init(res.data.streamUrl)
      })
    }
  })
}

/**
 * 获取历史视频
 */
function getHistoricalVideos() {
  // queryHistory(dataInfo.value.imei, 3, '2024-05-01 00:00:00', '2024-05-05 00:00:00').then(
  //   (res) => {}
  // )
}
function tabChange(val) {
  switch (val) {
    case 'second':
      freightRef.value.init(dataInfo.value.otherInfo)
      break
  }
}

function handleClose() {
  dialogVisible.value = false
  activeName.value = 'first'

  const channelNames = jt1078AvsetAnalysis(deviceInfo.value.jt1078Avch, deviceInfo.value.jt1078Avset)
  if (channelNames.length === 0) {
    return
  }
  for (let i = 0; i < channelNames.length; i++) {
    let cl = channelNames[i]
    avControl(dataInfo.value.imei, cl.channel).then((res) => {})
  }
}
defineExpose({
  init
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="运单详情" fullscreen :before-close="handleClose" destroy-on-close>
    <div class="content">
      <div class="info">
        <el-descriptions :title="`运单编号`" :column="1">
          <el-descriptions-item label="运单状态">
            <el-tag size="small">{{ dataInfo?.status ? '进行中' : '未开始' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="计划拉运时间">{{ dataInfo?.planningTime }}</el-descriptions-item>
          <el-descriptions-item label="货源名称">{{ dataInfo?.sourceName }}</el-descriptions-item>
          <el-descriptions-item label="货源类型">{{ dataInfo?.sourceType }}</el-descriptions-item>
          <el-descriptions-item label="货物类型">{{ dataInfo?.goodsType }}</el-descriptions-item>
          <el-descriptions-item label="车队名称">{{ dataInfo?.teamName }}</el-descriptions-item>
          <el-descriptions-item label="司机姓名">{{ dataInfo?.driverIName }}</el-descriptions-item>
          <el-descriptions-item label="车辆车牌号">{{ dataInfo?.plateNo }}</el-descriptions-item>
          <el-descriptions-item label="装货站点">{{ dataInfo?.mineName }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="right">
        <div class="top">
          <div class="camera">
            <div v-for="(num, i) in 4" :key="num" class="camera_item">
              <VuePlayer :ref="(el) => (videoRefs[i] = el)" :keys="num"></VuePlayer>
            </div>
          </div>
          <div>
            <!-- <real-time-track ref="trackRef"></real-time-track> -->
          </div>
        </div>
        <div class="bottom">
          <el-tabs v-model="activeName" @tab-change="tabChange">
            <el-tab-pane label="报警信息" name="first">
              <el-table :data="alarmData">
                <el-table-column label="报警类型" prop="type"></el-table-column>
                <el-table-column label="报警开始时间" prop="occurTime"></el-table-column>
                <el-table-column label="报警结束时间" prop="endTime"></el-table-column>
                <el-table-column label="报警等级" prop="level"></el-table-column>
                <el-table-column label="状态">
                  <template #default="scope">{{ scope.row.processStatus ? '已处理' : '未处理' }}</template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="装卸货时长" name="second">
              <FreightTimeCount ref="freightRef"></FreightTimeCount>
            </el-tab-pane>
            <el-tab-pane label="视频回放" name="third"> </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.content {
  display: flex;
}
.camera_item {
  box-sizing: border-box;
  background-color: black;
  border: 1px solid;
  width: 50%;
}
.content > .right {
  flex: 1;
}
.info {
  max-width: 350px;
  min-width: 300px;
}
.right {
  display: flex;
  flex-direction: column;
}
.top {
  display: flex;
}
.bottom {
}
.top > div {
  flex: 1;
}
.camera {
  display: flex;
  flex-wrap: wrap;
}
.camera > div {
  width: 50%;
  height: 200px;
}
.channel {
  display: flex;
}
.channel > div {
  flex: 1;
}
</style>
